<?php 
// Start Session before anything else
if(!isset($_SESSION))
	session_start();

// Include Required Files
require_once("../../includes/common.php");

// Initialize variables
global $file, $subsection, $section;
$mem_id=isset($_GET['mem_id']) ? $_GET['mem_id'] : NULL;
$dFlag = false;
$file=isset($file)? $file :"home";
$counters = Array();
$iTime = microtime(true);   // Script start time
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
$section = isset($_REQUEST['section']) ? $_REQUEST['section'] : null;
$subsection = isset($_REQUEST['sub']) ? $_REQUEST['sub'] : null;
$date = isset($_REQUEST['date']) ? $_REQUEST['date'] : "";
$userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null; 
$passWord = isset($_REQUEST['pass']) ? $_REQUEST['pass'] : null;
$currentDate=getCurrentDateTime();
$redirect=NULL;
$notification=NULL;
$actionString=NULL;

$skipandRedirect=FALSE;
// GET DB Connection
getConnection();



// Set the Default Error Handler
set_error_handler("defaultErrorHandler");

//Log Out
if($action == "logout") {
	
	// Unset all session variables
	foreach($_SESSION as $n=>$v) {
		unset($_SESSION[$n]);
	}
	
	$redirect = (isset($_GET['redirect'])) ? "?redirect=".urlencode($_GET['redirect']) : "";
	
	// Redirect to Home Page
	header( "Location: ./../index.php{$redirect}" ) ;
	echo "Redirecting";
	die();
	return;
}

// If user form has been submitted, proceed with login validation
if(($userId !=null && $passWord!=null)) {
	$userId = sanitizeData($userId);
	$pass = md5($passWord);
	
	//for admin login
	if($userId=="admin" && $pass=="admin"){
		$_SESSION['supAdminId'] = TRUE;
		$_SESSION['mem_id'] = "-1";
		$redirect = "./admin/v1";
		// Redirect to the Home Page
		header( 'Location: '.$redirect ) ;
		die();
	}
}
else{
	// If session already containts the admin
	if(isset($_SESSION) && isset($_SESSION['supAdminId']) && $_SESSION['supAdminId']==TRUE) {
		
	}else{
	// do some thing for non logged in users
		$redirect = "../../";
		header( 'Location: '.$redirect ) ;
		die();

	}
}
//Process Form Data

if(isset($_REQUEST['data'])) {
	global $frefs;
	dump_var("Yes there is process data",$_REQUEST);
	$fref = $_REQUEST['fref']; 
	dump_var("Table reference data ",$_REQUEST['fref']);
	dump_var("Table hashes ",$frefs);
	// Sanatize Input Data
	$_REQUEST['data'] = sanitizeData($_REQUEST['data']);
	// Check if the hash in $fref matched existing forms and proceed accordingly
	if(in_array($fref,$frefs)) {
		$skipandRedirect=TRUE;
		$fileDetails=NULL;
		$data=$_REQUEST['data'];
		
		switch($fref) {
			case md5(PAYMENT_RECIEVED):
				$res=AdminActivities::precossRecievedPayment($data);
				 if( $res >0){
					//success
					$notification=["status"=>"success","msg"=>"Payement Process Is Successfully Done"];
					
				 }else{
					//error
					$notification=["status"=>"error","msg"=>"Error in processing the payment. Please try again"];
				 }
				 $redirect="./payment.php";
			break;
			
			case md5(PAYMENT_MADE):
				$res=AdminActivities::makePayment($data);
				 if( $res >0){
					//success
					$notification=["status"=>"success","msg"=>"Payement Process Is Successfully Done"];
					
				 }else{
					//error
					$notification=["status"=>"error","msg"=>"Error in processing the payment. Please try again"];
				 }
				 $redirect="./payment.php";
			break;
			
			case md5(MEMBERS):
				$res=AdminActivities::updateMemberDetails($data,$_POST["mem_id"]);
				if( $res >0){
					//success
					$notification=["status"=>"success","msg"=>"Updated"];
					
				 }else{
					//error
					$notification=["status"=>"error","msg"=>"Error in updating. Please try again"];
				 }
				 $redirect="./memberDetails.php";
			break;
			
			case md5(EXTRA_COLLECTION):
				$res=AdminActivities::insertNewExtraCollection($data);
				 if( $res >0){
					//success
					$notification=["status"=>"success","msg"=>"Extra Collection is registered"];
					
				 }else{
					//error
					$notification=["status"=>"error","msg"=>"Error in processing registration of Extra Collection. Please try again"];
				 }
				 $redirect="./payment.php";
			break;
			
		}
		
		if(isset($notification)) { 
			$_SESSION['notification']=$notification;
		}
		
	} 
	else 
		dump_var("Not found a relevent processor for Data",$_REQUEST);
}

//Including index
if($skipandRedirect==FALSE){
	include_once("./templates/index.tpl");
}
else{
	if(isset($redirect)){
		header('Location:'.$redirect);
		die();
	}
}

// CLOSE DB Connection
closeConnection();

// Log the time taken for the script to run and the database counters 
dump_var("Page Load Time:  ".(microtime(true)-$iTime)." seconds",null);
dump_var("Showing Counters",$counters);

// Log Time to Load to gauge performance
writeToLogFile("{$file} {$section} {$subsection} \t\tLoad Time:  ".(microtime(true)-$iTime)." seconds");
writeToLogFile("SQL Stats ".json_encode($counters));


// Show the var dumps 
if($dFlag) {
	$js = <<<EOt
	<script>
	function cl(string) {
		console.log(string);
	}
	</script>
EOt;
	echo $js;
	echo "<div id=\"footer\" style=\"margin-left:auto;margin-right:auto;width:960px;padding:5px;\">";
	show_var_dump();
	echo "</div>";
}else {
	$js = <<<EOt
	<script>
	function cl(string) {
		return string;
	}
	</script>
EOt;
	echo $js;
}
?>